//#version 120
//precision mediump float;
uniform mat4 uMVPMatrix; // 总变化矩阵
uniform mat4 uMMatrix;// 变化矩阵
uniform vec3 uCamera;// 摄像机位置
uniform vec3 uLightLocation;// 太阳光源位置
attribute vec3 aPosition;//顶点的位置
attribute vec2 aTexture;//纹理坐标
attribute vec3 aNormal;// 法向量

varying vec2 vTextureCoord;// 片元着色器
varying vec4 vAmbient; // 环境光
varying vec4 vDiffuse; //散射光
varying vec4 vSpecular;//镜面光

//

void pointLight(
in vec3 normal,
inout vec4 ambient,
inout vec4 diffuse,
inout vec4 specualr,
in vec3 lightLocation,
in vec4 lightAmbient,
in vec4 lightDiffuse,
in vec4 lightSpecular
)
{
    ambient = lightAmbient;
    vec3 normalTarget = aPosition + normal; // 计算当前位置的法向量
    //计算经过矩阵变化后的法向量
    vec3 newNormal = (uMMatrix * vec4(normalTarget,1)).xyz - (uMMatrix * vec4(aPosition ,1)).xyz;
    //向量规格化
    newNormal = normalize(newNormal);
    //计算从表面到摄像机的位置向量
    vec3 eye = normalize(uCamera - (uMMatrix * vec4(aPosition,1)).xyz);
    //计算从表面到光源的位置向量
    vec3 position = normalize(lightLocation - (uMMatrix * vec4(aPosition,1)).xyz);
    // 计算摄像机和光源的半向量
    vec3 halfVector = normalize(eye + position);
    // 粗糙度越小越光滑
    float shininess = 50.0;
    //求法向量，光源点积与0 的最大值
    float mDotPosition = max(0.0,dot(newNormal,position));
    //计算散射光的强度
    diffuse = lightDiffuse * mDotPosition;
    //矩阵变化的法向量与摄像机位置向量，光源向量夹角的点击
    float mDotHalfVector = dot(newNormal,halfVector);
    //镜面反射光
    float mPowerFator = max(0.0,pow(mDotHalfVector,shininess));
    //计算镜面反射光
    specualr = lightSpecular * mPowerFator;
}

void main() {

    //根据总变化矩阵计算此次绘制此顶点的位置
    gl_Position = uMVPMatrix * vec4(aPosition,1);
    vec4 ambientValue = vec4(0.0,0.0,0.0,0.0);
    vec4 diffuseValue = vec4(0.0,0.0,0.0,0.0);
    vec4 specularValue = vec4(0.0,0.0,0.0,0.0);

    pointLight(normalize(aNormal),ambientValue,diffuseValue,specularValue,uLightLocation,
    vec4(0.05,0.05,0.05,1.0),vec4(1.0,1.0,1.0,1.0),vec4(0.3,0.3,0.3,1.0));
    vAmbient = ambientValue;
    vDiffuse = diffuseValue;
    vSpecular = specularValue;
    //将纹理坐标传递给片元着色器

}
